/**
 * @param {number[]} beans
 * @return {number}
 */
 var minimumRemoval = function(beans) {
  const n = beans.length
  beans.sort((a,b) => a-b)
  const idx = {}
  const sum = new Array(n+1).fill(0)
  for(let i = 1; i<=n; i++){
    sum[i] = sum[i-1] + beans[i-1]
    let x = beans[i-1]
    idx[x] = idx[x] ?? []
    idx[x].push(i)
  }
  let ans = Infinity
  for(let x of beans){
    ans = Math.min(ans, calc(x))
  }
  return ans
  function calc(x) {
    const arr = idx[x]
    let min = arr[0], max = arr[arr.length-1]
    let suffix = sum[n] - sum[max] - x * (n-max)
    return sum[min-1] + suffix;
  }
};
